<template>
  <div @click="indexNum = -1">
    <div class="major" style="margin-top: 30px">
      <div class="major-left">专业选择</div>
      <div class="major-right">
        <el-popover
          v-for="(item, index) in majorList"
          :visible="indexNum == index"
          :key="index"
          placement="bottom"
          width="auto"
        >
          <template #reference>
            <div
              class="major-size alitem"
              :class="indexNum === index ? 'active' : ''"
              @click.stop="clickChange(index)"
            >
              <div>{{ item.name }}({{ item.childCount }})&nbsp;</div>
              <el-icon>
                <ArrowDown />
              </el-icon>
            </div>
          </template>
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
            >全部</el-checkbox
          >
          <el-checkbox-group
            v-model="tempSelMajors"
            @change="handleCheckedCitiesChange"
            style="display: flex; flex-wrap: wrap; width: 500px"
          >
            <el-checkbox
              v-for="major in item.majors"
              :key="major"
              :label="major"
              >{{ major.name }}</el-checkbox
            >
          </el-checkbox-group>
          <div class="right matop">
            <el-button @click="indexNum = -1">取消</el-button>
            <el-button type="primary" @click="onClickCheckboxConfirm"
              >确定</el-button
            >
          </div>
        </el-popover>
      </div>
    </div>
    <!-- <div class="major">
			<div class="major-left">招生类型</div>
			<div class="major-right">
				<div class="major-size" v-for="(item,index) in studentType" :key="index">{{item}}</div>
			</div>
		</div> -->
    <!-- <div class="major">
			<div class="major-left">限报要求</div>
			<div class="major-right">
				<el-switch v-model="value1" active-text="色盲色弱" />
				<el-switch v-model="value1" active-text="单科成绩" />
				<el-switch v-model="value1" active-text="语种要求" />
			</div>
		</div> -->
    <el-row class="matop">
      <el-col :span="12">
        <div class="alitem">
          <el-input
            ref="buttonRef"
            v-model="searchKey"
            style="width: 240px"
            placeholder="输入意向专业"
            clearable
            @input="searchKeyInput"
            @focus="isShowSearchPop = true"
            @blur="isShowSearchPop = false"
          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
          <div
            v-show="isShowSearchPop && searchList.length > 0"
            class="search-popover"
          >
            <div
              class="curr"
              v-for="(item, index) in searchList"
              @mousedown.native="onClickSearchItem(item, index)"
            >
              <div style="padding: 5px 0">
                {{ index == 0 ? '在筛选条件中搜索 "' + item + '"' : item.name }}
              </div>
              <div
                v-if="index + 1 < searchList.length"
                style="width: 100%; height: 1px; background-color: #eee"
              ></div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { allMajor, searchMajor } from '@/api/appv2/appv1.js';
import userSearch from '@/store/modules/searchInfo.js';
import _ from 'lodash';

const userSearchVal = userSearch();

const props = defineProps({
  // 学生ID
  studentId: {
    type: Number,
    default: 0,
  },
  // 批次线信息
  batchInfo: {
    type: Object,
    default: {},
  },
});

const indexNum = ref(-1);

const searchList = ref([]); // 模糊搜索数据源
const majorList = ref([]); // 专业筛选数据源
const selMajors = ref([]); // 选中的专业筛选数据
const checkAll = ref(false);

const tempSelMajors = ref([]);

const searchKey = ref(''); // 搜索关键词
const isShowSearchPop = ref(false); // 是否显示搜索pop

// 模糊搜索
const searchItem = reactive({
  code: 0,
  name: '',
  type: 'msearch',
});

function getallMajor() {
  const data = {
    studentId: props.studentId,
  };

  if (props.batchInfo.is_batch == 1 || props.batchInfo.batch.includes('专')) {
    data.majorsZK = 1;
  } else {
    data.majorsBK = 1;
  }
  allMajor(data).then((res) => {
    majorList.value = res.data.majorsBK || res.data.majorsZK;
  });
}
getallMajor();

// 搜索输入值改变
const searchKeyInput = _.throttle((val) => {
  if (val.length >= 2) {
    searchMajor({
      search: val,
      pageSize: 1000,
      studentId: props.studentId,
    }).then((res) => {
      searchList.value = res.data;

      searchList.value.splice(0, 0, searchKey.value);
      isShowSearchPop.value = true;
    });
  } else {
    searchList.value = [];
    isShowSearchPop.value = false;
  }
}, 800);

/**
 * 点击全选
 * @param {Boolean} val 是否全选
 */
function handleCheckAllChange(val) {
  if (val) {
    let majors = majorList.value[indexNum.value].majors;
    majors.forEach((item) => {
      let arr = tempSelMajors.value.filter((i) => i.code == item.code);

      // 判断是否已存在
      if (arr.length == 0) {
        tempSelMajors.value.push(item);
      }
    });
  } else {
    let majors = majorList.value[indexNum.value].majors;
    majors.forEach((item) => {
      tempSelMajors.value = tempSelMajors.value.filter(
        (i) => i.code != item.code
      );
    });
  }
}

// 点击单个筛选专业
const handleCheckedCitiesChange = (value) => {
  let item = value[value.length - 1];
  // 判断是否有相同code数据在数组中
  let arr = tempSelMajors.value.filter((i) => i.code == item.code);

  if (arr.length >= 2) {
    // 有相同数据，删除第一个添加的该专业
    let index = tempSelMajors.value.findIndex((i) => i.code == item.code);
    tempSelMajors.value.splice(index, 1);
  }

  checkAllChange();
};

/**
 * 点击专业组
 * @param {Number} val 专业组下标
 */
function clickChange(val) {
  if (indexNum.value == val) {
    indexNum.value = -1;
    return;
  } else {
    indexNum.value = val;
  }

  tempSelMajors.value = JSON.parse(JSON.stringify(selMajors.value));

  checkAllChange();
}

// 全选状态改变
function checkAllChange() {
  // 统计当前专业组下已选中专业数
  let majors = majorList.value[indexNum.value].majors;
  let num = 0;
  majors.forEach((item) => {
    let arr = tempSelMajors.value.filter((i) => i.code == item.code);
    num += arr.length;
  });
  // 判断是否全选
  checkAll.value = num >= majors.length;
}

// 确定筛选条件
function onClickCheckboxConfirm() {
  selMajors.value = tempSelMajors.value;
  indexNum.value = -1;

  saveMajorInfo();
}

/**
 * 点击搜素选项
 * @param {Object} item 专业数据
 * @param {Number} index 下标
 */
function onClickSearchItem(item, index) {
  if (index == 0) {
    // 模糊搜索
    searchItem.name = item;
    saveMajorInfo();
  } else {
    // 精准专业搜索
    let index = selMajors.value.findIndex((i) => i.code == item.code);
    if (index < 0) {
      selMajors.value.push(item);
      saveMajorInfo();
    }
  }

  // 添加后清除搜索数据
  searchKey.value = '';
  searchList.value = [];
  isShowSearchPop.value = false;
}

// 保存专业筛选数据到仓库
function saveMajorInfo() {
  let searchArray = [];
  selMajors.value.forEach((item) => {
    searchArray.push({
      name: item.name,
      code: item.code,
      type: 'major',
    });
  });

  // 判断是否存在模糊搜索
  if (searchItem.name.length > 0) {
    searchArray.push(searchItem);
  }

  userSearchVal.saveMajorInfoChange(searchArray); // 保存到 store 中
}

/**
 * 删除某条筛选条件
 * @param {Object} item {type:'类型', code:'id', name:'标题'}
 */
function deleteScreenItem(item) {
  if (item.type == searchItem.type) {
    searchItem.name = '';
  } else {
    selMajors.value = selMajors.value.filter((i) => i.code != item.code);
  }

  saveMajorInfo();
}

function deleteAll() {
  selMajors.value = [];
  tempSelMajors.value = [];
  searchItem.name = '';
  saveMajorInfo();
}

defineExpose({
  deleteScreenItem,
  deleteAll,
});
</script>
<style lang="scss" scoped>
.flexend {
  div {
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-right: 20px;
  }
}

.major {
  display: flex;
  margin-top: 10px;

  .major-left {
    width: 100px;
    font-size: 14px;
    text-align: center;
    color: #9b9b9b;
  }

  .major-right {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .major-size {
      font-size: 14px;
      margin-bottom: 12px;
      padding: 4px 16px;
      margin-right: 10px;
      text-align: center;
      border: 1px solid #e5e6eb;
      border-radius: 4px;
      cursor: pointer;
      color: #4e5969;
    }

    .active {
      border: 1px solid #004cf7;
      color: #004cf7;
    }
  }
}
.search-popover {
  position: absolute;
  top: 40px;
  left: 0;
  width: 240px;
  height: 200px;
  overflow: auto;
  background-color: white;
  z-index: 999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  border: 1px solid #c9cdd4;
  padding: 0 10px;
  font-size: 14px;
}
</style>
